package com.leyou.search.service.impl;

import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.search.service.StaticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@Service
@Slf4j
public class StaticServiceImpl implements StaticService {

    private static final String TEMPLATE_VAR_NAME = "categories";

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Value("${ly.static.pageSavePath}")
    private String pageSaveDir;
    @Value("${ly.static.pageTemplate}")
    private String pageTemplate;

    /**
     * 页面静态化服务
     * @return
     */
    @Override
    public Boolean staticIfyIndex(){
        //1.远程调用Item服务获取 所有分类信息，接收一个json字符串
        String categoriesJson = itemClient.queryCategories();
        try {
            createItemHtml(categoriesJson);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 静态模板生成方法
     * @param categoriesJson 首页分类信息
     */
    private void createItemHtml(String categoriesJson) {
        // 上下文，准备模型数据
        Context context = new Context();

        // 调用之前写好的加载数据方法
        context.setVariable(TEMPLATE_VAR_NAME,categoriesJson);
        // 准备文件路径
        File dir = new File(pageSaveDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                // 创建失败，抛出异常
                log.error("[模板方法]创建静态页目录失败，目录地址：{}", dir.getAbsolutePath());
                throw new LyException(500,"失败");
            }
        }
        File filePath = new File(dir,  "index.html");
        // 准备输出流
        try (PrintWriter writer = new PrintWriter(filePath, "UTF-8")) {
            templateEngine.process(pageTemplate, context, writer);
        } catch (IOException e) {
            log.error("[模板方法]静态页生成失败，原因：{}", e);
            throw new LyException(500,"服务异常");
        }
    }
}
